package com.mxw.controller;

import com.mxw.entity.Resource;
import com.mxw.entity.UserInfo;
import com.mxw.model.PageRequest;
import com.mxw.model.PageResult;
import com.mxw.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class ResourceController {

    @Autowired
    private ResourceService resourceService;

    /**
     * 访问首页
     * @param model 视图模型
     * @param keyword 搜索关键词
     * @return 返回首页模板
     */
    @GetMapping("/")
    public String index(Model model, @RequestParam(required = false) String keyword) {
        // 创建默认分页请求，每页8条数据
        PageRequest request = new PageRequest();
        request.setPageNum(1);
        request.setPageSize(8);
        request.setKeyword(keyword);
        
        // 获取第一页数据
        PageResult<Resource> pageResult = resourceService.getResourcePage(request);
        
        // 将数据添加到模型中
        model.addAttribute("resources", pageResult.getList());
        model.addAttribute("total", pageResult.getTotal());
        model.addAttribute("currentPage", pageResult.getPageNum());
        model.addAttribute("totalPages", pageResult.getPages());
        model.addAttribute("keyword", keyword);
        
        return "index";
    }

    /**
     * 分页获取资源列表
     * @param request 分页请求参数
     * @return 分页结果
     */
    @GetMapping("/api/resources")
    @ResponseBody
    public PageResult<Resource> getResourcePage(PageRequest request) {
        return resourceService.getResourcePage(request);
    }

    /**
     * 根据ID获取资源详情
     * @param id 资源ID
     * @param model 视图模型
     * @param session HTTP会话
     * @return 资源详情页面
     */
    @GetMapping("/resource/id/{id}")
    public String getResourceDetailById(@PathVariable Integer id, Model model, HttpSession session) {
        // 获取资源详情
        Resource resource = resourceService.getResourceById(id);
        model.addAttribute("resource", resource);
        
        // 获取相关资源推荐
        if (resource != null) {
            PageRequest request = new PageRequest();
            request.setPageNum(1);
            request.setPageSize(2);
            PageResult<Resource> relatedResources = resourceService.getRelatedResources(id, request);
            model.addAttribute("relatedResources", relatedResources.getList());
            
            // 获取收藏状态
            UserInfo user = (UserInfo) session.getAttribute("user");
            boolean isCollected = user != null && resourceService.isResourceCollected(id, user.getId());
            model.addAttribute("isCollected", isCollected);
        }
        
        return "resource-detail";
    }

    /**
     * 根据标题获取资源详情
     * @param title 资源标题
     * @param model 视图模型
     * @return 资源详情页面
     */
    @GetMapping("/resource/title/{title}")
    public String getResourceDetailByTitle(@PathVariable String title, Model model) {
        // 获取资源详情
        Resource resource = resourceService.getResourceByTitle(title);
        if (resource != null) {
            // 重定向到ID路由
            return "redirect:/resource/id/" + resource.getId();
        }
        model.addAttribute("resource", null);
        return "resource-detail";
    }

    /**
     * 收藏/取消收藏资源
     * @param id 资源ID
     * @param session HTTP会话
     * @return 操作结果
     */
    @PostMapping("/api/resource/{id}/collection")
    @ResponseBody
    public ResponseEntity<?> collectResource(@PathVariable Integer id, HttpSession session) {
        // 获取当前登录用户
        UserInfo user = (UserInfo) session.getAttribute("user");
        if (user == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "请先登录");
            return ResponseEntity.status(401).body(response);
        }

        try {
            resourceService.collectResource(id, user.getId());
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "收藏成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "收藏失败，请稍后重试");
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 取消收藏资源
     * @param id 资源ID
     * @param session HTTP会话
     * @return 操作结果
     */
    @DeleteMapping("/api/resource/{id}/collection")
    @ResponseBody
    public ResponseEntity<?> uncollectResource(@PathVariable Integer id, HttpSession session) {
        // 获取当前登录用户
        UserInfo user = (UserInfo) session.getAttribute("user");
        if (user == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "请先登录");
            return ResponseEntity.status(401).body(response);
        }

        try {
            resourceService.uncollectResource(id, user.getId());
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "取消收藏成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "取消收藏失败，请稍后重试");
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 访问收藏页面
     * @param model 视图模型
     * @param session HTTP会话
     * @return 收藏页面
     */
    @GetMapping("/my-collections")
    public String myCollections(Model model, HttpSession session) {
        // 获取当前登录用户
        UserInfo user = (UserInfo) session.getAttribute("user");
        if (user == null) {
            // 如果用户未登录，重定向到登录页面
            return "redirect:/login";
        }

        // 获取用户的收藏列表
        PageRequest request = new PageRequest();
        request.setPageNum(1);
        request.setPageSize(12); // 每页显示12个收藏
        PageResult<Resource> collections = resourceService.getUserCollections(user.getId(), request);
        
        // 将数据添加到模型中
        model.addAttribute("collections", collections.getList());
        model.addAttribute("total", collections.getTotal());
        
        return "favorites";
    }
}
